package com.piece.module.spider.websocket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.piece.module.spider.context.SpiderWebSocketContext;
import com.piece.module.spider.context.SpiderWebSocketEvent;
import com.piece.module.spider.executor.Spider;
import com.piece.module.spider.util.SpiderFlowUtil;
import org.springframework.stereotype.Component;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

/**
 * WebSocket通讯编辑服务
 */
@Component
@ServerEndpoint("/spider_ws")
public class SpiderWebSocketEditorServer {

    public static Spider spider;

    private SpiderWebSocketContext context;

    @OnMessage
    public void onMessage(String message, Session session) {
        JSONObject event = JSON.parseObject(message);
        String eventType = event.getString("eventType");
        boolean isDebug = "debug".equalsIgnoreCase(eventType);
        if ("test".equalsIgnoreCase(eventType) || isDebug) {
            context = new SpiderWebSocketContext(session);
            context.setDebug(isDebug);
            context.setRunning(true);
            new Thread(() -> {
                String xml = event.getString("message");
                if (null != xml) {
                    spider.runWithTest(SpiderFlowUtil.loadXMLFromString(xml), context);
                    context.write(new SpiderWebSocketEvent<>("finish", null));
                } else {
                    context.write(new SpiderWebSocketEvent<>("error", "xml不正确！"));
                }
                context.setRunning(false);
            }).start();
        } else if ("stop".equals(eventType) && null != context) {
            context.setRunning(false);
            context.stop();
        } else if("resume".equalsIgnoreCase(eventType) && null != context){
            context.resume();
        }
    }

    @OnClose
    public void onClose(Session session) {
        context.setRunning(false);
        context.stop();
    }
}
